package com.fs.web.base.aspect;

import com.fs.web.base.utils.ApplicationUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author TiddlerCJ
 * @desc http请求，日志拦截处理  用来拦截http请求，并且做详细记录
 */
@Slf4j
@Aspect
@Component
public class HttpAspect {

	@Pointcut("execution(* com..*.*Controller.*(..))")
	public void log(){}

	/**
	 * 在log方法执行之前执行的逻辑
	 * @param joinPoint
	 */
	@Before("log()")
	public void before(JoinPoint joinPoint){
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		log.info("url:"+request.getRequestURL()+" method:"+ request.getMethod()+" ip:"+ ApplicationUtils.getRemoteHost()+" class_method:"+ joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
	}

	/**
	 * 在log方法执行之后执行的代码
	 */
	@After("log()")
	public void after(){
		//System.out.println("=====After======");
	}

	/**
	 * 可以获取执行log方法时方法的 返回值
	 * @param obj
	 */
	@AfterReturning(pointcut="log()",returning="obj")
	public void onAfterReturning(Object obj){
		//System.out.println("=====onAfterReturning======");
		//System.out.println("response: "+ JSON.toJSONString(obj));
	}
}
